#include "source.h"
#include "gps.h"
#include "core1.h"

#define UART_ID uart0
#define BAUD_RATE 460800
#define UART_TX_PIN 0
#define UART_RX_PIN 1

const uint32_t MINSEC_MASK = 63;
const uint32_t HR_MASK = 31;

char buffer[100] = {0};
int pos = 0;

void process_time() {
  struct GpsTime time;
  if (nmea_sentence_to_time(buffer, &time)) {
    uint32_t data = (time.hour & HR_MASK) << 12 |
                    (time.minute & MINSEC_MASK) << 6 |
                    (time.second & MINSEC_MASK);
    multicore_fifo_push_blocking(data);
  }
}

void on_uart_rx() {
  while (uart_is_readable(UART_ID)) {
    uint8_t ch = uart_getc(UART_ID);
    if (ch == '\n') {
      buffer[pos] = '\0';
      pos = 0;
      process_time();
    } else if (pos < 99) {
      buffer[pos++] = ch;
    }
  }
}

int main() {
  stdio_init_all();
  multicore_launch_core1(core1_entry);

  uart_init(UART_ID, BAUD_RATE);
  gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART);
  gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);

  int UART_IRQ = UART_ID == uart0 ? UART0_IRQ : UART1_IRQ;
  irq_set_exclusive_handler(UART_IRQ, on_uart_rx);
  irq_set_enabled(UART_IRQ, true);
  uart_set_irq_enables(UART_ID, true, false);

  while (true) {
    tight_loop_contents();
  }

  return 0;
}
